package grdnlog.controller;

import grdnlog.bean.GardenLogConfig;
import grdnlog.bean.GardenLogEntry;
import grdnlog.service.GardenLogService;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@RequestMapping("/log")
@Controller
public class GardenLogController {

	@Autowired
	private GardenLogService gardenLogService;

	@ModelAttribute("entries")
	public List<GardenLogEntry> populateEntries() {
		final UserService userService = UserServiceFactory.getUserService();
		
		if (userService.isUserLoggedIn()) {
			User user = userService.getCurrentUser();
			List<GardenLogEntry> results = gardenLogService.getGardenLogEntries(user.getEmail());
			return new ArrayList<GardenLogEntry>(results);
		} else {
			return new ArrayList<GardenLogEntry>();
		}
	}

	@RequestMapping(method = RequestMethod.GET)
	public String home() {
		return "log";
	}
		
	@RequestMapping(params = "delete-entry", method = RequestMethod.POST)
	public String deleteEntry(@RequestParam("id") String entryId, GardenLogConfig entry, BindingResult result, SessionStatus status) {
		//TODO prevent deleting other user's entries
		final String userId = "does nothing";
		try {
			gardenLogService.deleteGardenLogEntry(entryId, userId);
			status.setComplete();
		} catch (Exception e) {
			result.reject("error.entry.delete", e.getLocalizedMessage());
		}
		
		return "redirect:log";
	}
	
	@RequestMapping(params = "sync", method = RequestMethod.POST)
	public String sync(GardenLogConfig config, BindingResult result, SessionStatus status) {
				
		if (result.hasErrors()) {
			return "log";
		} else {
			final UserService userService = UserServiceFactory.getUserService();
			
			if (userService.isUserLoggedIn()) {
				User user = userService.getCurrentUser();
				gardenLogService.syncGardenLogEntries(user.getEmail());
			} else {
				result.reject("You must be logged in!");
				return "log";
			}			
			
			return "redirect:log";
		}
	}
	
}
